package com.enbatis.mybatisplugs.service.impl;

import com.enbatis.mybatisplugs.base.Account;
import com.enbatis.mybatisplugs.base.BaseServiceImpl;

import com.enbatis.mybatisplugs.commons.sql.Wrapper;
import com.enbatis.mybatisplugs.commons.utils.IdWorker;
import com.enbatis.mybatisplugs.entity.FoodList;
import com.enbatis.mybatisplugs.entity.Recipes;
import com.enbatis.mybatisplugs.mapper.FoodListMapper;
import com.enbatis.mybatisplugs.service.FoodListService;
import com.enbatis.mybatisplugs.service.RecipesService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.xwpf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
* 描述：
* @author wwd
* @date 2020-10-26 10:54:21
*/

@Service
public class FoodListServiceImpl extends BaseServiceImpl<FoodListMapper,FoodList > implements FoodListService {

    @Autowired
    private RecipesService recipesService;

    @Override
    public boolean uploadFoodList(MultipartFile file, Account account) {

        XWPFDocument document = null;
        InputStream io=null;
        try {
            io = file.getInputStream();
            document=  new XWPFDocument(io);
        }catch (Exception e){
            e.getMessage();
            e.printStackTrace();
        }
        List<XWPFTable> tables= document.getTables();
        Recipes recipes = new Recipes();
        recipes.setId(IdWorker.getId());
        recipes.setPerson(account.getUsername());
        recipes.setPersonId(account.getId());
        recipes.setCtime(new Date());
        recipes.setName(file.getOriginalFilename().replace(".docx","")+"食谱");
        recipes.setTimes(file.getOriginalFilename().replace(".docx",""));
        List<FoodList> savefoodListList = new ArrayList<>();

        for (XWPFTable table:tables) {
          int num=   table.getNumberOfRows();
            for (int i = 0; i < num; i++) {
                XWPFTableRow row= table.getRow(i);
                List<XWPFTableCell> tableCells=  row.getTableCells();
                if (i==0||i==1){
                    continue;
                }
                int column=tableCells.size();
                FoodList foodList = new FoodList();
                for (int m = 0; m < column; m++) {
                    foodList.setRecipesId(recipes.getId());
                    XWPFTableCell cell= tableCells.get(m);
                    if (m==0){
                        foodList.setWhatDay(cell.getText());
                    }else if (1==m){
                        StringBuffer sb = new StringBuffer();
                        List<XWPFParagraph> paragraphs=  cell.getParagraphs();
                        for (XWPFParagraph paragraph:paragraphs) {
                            paragraph.getText();
                            sb.append(paragraph.getText()).append(" ");
                        }
                        foodList.setBreakfast(sb.toString());
                    }else if (2==m){
                        foodList.setIngredientEarly(cell.getText());
                    }else if (3==m){

                        StringBuffer sb = new StringBuffer();
                        List<XWPFParagraph> paragraphs=  cell.getParagraphs();
                        for (XWPFParagraph paragraph:paragraphs) {
                            paragraph.getText();
                            sb.append(paragraph.getText().replaceAll("\\d+","")).append(" ");
                        }
                        foodList.setEarlySnack(sb.toString());


                    }else if (4==m){
                        StringBuffer sb = new StringBuffer();
                        List<XWPFParagraph> paragraphs=  cell.getParagraphs();
                        for (XWPFParagraph paragraph:paragraphs) {
                            paragraph.getText();
                            sb.append(paragraph.getText()).append(" ");
                        }
                        foodList.setLunch(sb.toString());
                    }else if (5==m){
                        foodList.setIngredientLunch(cell.getText());
                    }else if (6==m){
                        StringBuffer sb = new StringBuffer();
                        List<XWPFParagraph> paragraphs=  cell.getParagraphs();
                        for (XWPFParagraph paragraph:paragraphs) {
                            List<XWPFRun> runs=  paragraph.getRuns();
                            for (XWPFRun run:runs) {
                               if (run.isBold()){
                                   sb.append(run.toString()).append(" ") ;
                               }
                            }

                        }
                        foodList.setLunchSnack(sb.toString());
                    }


                }
                savefoodListList.add(foodList);
            }

        }
        if (recipesService.insert(recipes)!=null){
           if (CollectionUtils.isNotEmpty(savefoodListList)){
               saveBatch(savefoodListList);
           }
        }
        return true;
    }

    @Override
    public void export(HttpServletResponse response, Long id) {
        Recipes recipes = recipesService.getById(id);
        XWPFDocument xwpfDocument = new XWPFDocument();
        XWPFParagraph paragraph= xwpfDocument.createParagraph();
        paragraph.setAlignment(ParagraphAlignment.CENTER);
        XWPFRun run = paragraph.createRun();
        run.setText("青岛市市南区安徽路幼儿园幼儿食谱_"+recipes.getTimes());
        XWPFRun xxx=  paragraph.createRun();
        xxx.setText("\r\n");
         StringBuffer orderSb = new StringBuffer();
        orderSb.append(" case what_day ");

        orderSb.append(" when '一' then 1 ");
        orderSb.append(" when '二' then 2 ");
        orderSb.append(" when '三' then 3 ");
        orderSb.append(" when '四' then 4 ");
        orderSb.append(" when '五' then 5 ");
        orderSb.append(" end ");

        List<FoodList> foodListList = baseMapper.selectListFood(id);
        for (FoodList foodList:foodListList) {
            XWPFParagraph xwpfParagraph= xwpfDocument.createParagraph();
            paragraph.setAlignment(ParagraphAlignment.LEFT);
            XWPFRun xwpfRun=  xwpfParagraph.createRun();
            xwpfRun.setText("周"+foodList.getWhatDay()+"\r");

            XWPFRun xwpfRunZaoCan=  xwpfParagraph.createRun();
            xwpfRunZaoCan.setText("早餐："+foodList.getBreakfast()+"\r");

            XWPFRun xwpfRunZaoDian=  xwpfParagraph.createRun();
            xwpfRunZaoDian.setText("早点："+foodList.getEarlySnack()+"\r");


            XWPFRun xwpfRunWuCan=  xwpfParagraph.createRun();
            xwpfRunWuCan.setText("午餐："+foodList.getLunch()+"\r");

            XWPFRun xwpfRunWudian=  xwpfParagraph.createRun();
            xwpfRunWudian.setText("午点："+foodList.getLunchSnack()+"\r");

        }
        downloadDocx(response,""+recipes.getTimes()+".docx",xwpfDocument);
       try {
           xwpfDocument.close();
       }catch (Exception e){

       }
    }


    public void downloadDocx(HttpServletResponse response, String fileName, XWPFDocument doc) {
        response.reset();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        response.addHeader("Content-Disposition", String.format("attachment; filename=%s;charset=UTF-8", fileName));
        try (
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                OutputStream os = response.getOutputStream()
        ) {
            doc.write(bos);
            os.write(bos.toByteArray());
            os.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
